<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"flat"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="Singleton该文讲述了三种方法来创建单例, 各种方法的优点以及缺点，该文也介绍了另外一篇文章单例的Are Singletons Bad。 原文地址">
<meta property="og:type" content="article">
<meta property="og:title" content="Singleton">
<meta property="og:url" content="http://example.com/2018/12/21/Swift/Singleton/index.html">
<meta property="og:site_name" content="HR&#39;s Blog">
<meta property="og:description" content="Singleton该文讲述了三种方法来创建单例, 各种方法的优点以及缺点，该文也介绍了另外一篇文章单例的Are Singletons Bad。 原文地址">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2018-12-21T07:12:43.000Z">
<meta property="article:modified_time" content="2018-12-21T07:12:43.000Z">
<meta property="article:author" content="HR">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2018/12/21/Swift/Singleton/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>Singleton | HR's Blog</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-61905451-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-61905451-1');
      }
    </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">HR's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Swimming 🏊 in the sea🌊of code!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://example.com/2018/12/21/Swift/Singleton/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="HR">
      <meta itemprop="description" content="Swimming 🏊 in the sea🌊of code!">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HR's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Singleton
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2018-12-21 15:12:43" itemprop="dateCreated datePublished" datetime="2018-12-21T15:12:43+08:00">2018-12-21</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index"><span itemprop="name">Swift</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="Singleton"><a href="#Singleton" class="headerlink" title="Singleton"></a>Singleton</h1><p>该文讲述了三种方法来创建单例, 各种方法的优点以及缺点，该文也介绍了另外一篇文章单例的Are Singletons Bad。</p>
<p><a target="_blank" rel="noopener" href="https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift">原文地址</a></p>
<span id="more"></span>

<h1 id="What-Is-a-Singleton-and-How-To-Create-One-In-Swift"><a href="#What-Is-a-Singleton-and-How-To-Create-One-In-Swift" class="headerlink" title="What Is a Singleton and How To Create One In Swift"></a>What Is a Singleton and How To Create One In Swift</h1><p>The singleton pattern is a widely used design pattern in software development. Despite its popularity, it’s often considered an anti-pattern. Why is that? In this episode, I explain what the singleton pattern entails and how to create singletons in Swift.</p>
<h2 id="What-Is-a-Singleton"><a href="#What-Is-a-Singleton" class="headerlink" title="What Is a Singleton"></a>What Is a Singleton</h2><p>Singletons are easy to understand. The singleton pattern guarantees that only one instance of a class is instantiated. That’s simple. Right?</p>
<blockquote>
<p>The singleton pattern guarantees that only one instance of a class is instantiated.<br>单例模式保证只实例化一个类的一个实例。</p>
</blockquote>
<p>If you’ve worked with Apple’s frameworks, then chances are that you’ve already used the singleton pattern. Take a look at these examples. They probably look familiar.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Shared URL Session</span></span><br><span class="line"><span class="keyword">let</span> sharedURLSession <span class="operator">=</span> <span class="type">URLSession</span>.shared</span><br><span class="line"></span><br><span class="line"><span class="comment">// Default File Manager</span></span><br><span class="line"><span class="keyword">let</span> defaultFileManager <span class="operator">=</span> <span class="type">FileManager</span>.default</span><br><span class="line"></span><br><span class="line"><span class="comment">// Standard User Defaults</span></span><br><span class="line"><span class="keyword">let</span> standardUserDefaults <span class="operator">=</span> <span class="type">UserDefaults</span>.standard</span><br><span class="line"></span><br><span class="line"><span class="comment">// Default Payment Queue</span></span><br><span class="line"><span class="keyword">let</span> defaultPaymentQueue <span class="operator">=</span> <span class="type">SKPaymentQueue</span>.default()</span><br></pre></td></tr></table></figure>

<p>The singleton pattern is a very useful pattern. There are times that you want to make sure only one instance of a class is instantiated and that your application only uses that instance. That’s the primary and only goal of the singleton pattern.</p>
<p>The default payment queue of the <strong>StoreKit</strong> framework is a fine example. An application should never create an instance of the <code>SKPaymentQueue</code> class. The operating system uses the <strong>StoreKit</strong> framework to create a payment queue, which your application can use. The default payment queue is accessible through the <code>default()</code> class method of the <code>SKPaymentQueue</code> class. This is a good example of how the singleton pattern should be applied.</p>
<h2 id="Global-Access"><a href="#Global-Access" class="headerlink" title="Global Access"></a>Global Access</h2><p>But the singleton pattern has a side effect that’s often the true reason for adopting the singleton pattern, <strong>global access</strong>. But having global access to the singleton object is no more than a side effect of the singleton pattern.</p>
<p>Unfortunately, many developers use the singleton pattern to have easy access to the singleton object from anywhere in their project. The default payment queue is accessible through the <code>default()</code> class method. This means that any object in a project can access the default payment queue. While this is convenient, that convenience comes at a price.</p>
<p>If you want to learn more about the problems surrounding the singleton pattern, then I recommend reading <a target="_blank" rel="noopener" href="https://cocoacasts.com/are-singletons-bad/">Are Singletons Bad</a>. In that article, I discuss this topic in more detail.</p>
<h2 id="How-to-Create-a-Singleton-In-Swift"><a href="#How-to-Create-a-Singleton-In-Swift" class="headerlink" title="How to Create a Singleton In Swift"></a>How to Create a Singleton In Swift</h2><p>In this episode, I list two recipes for implementing the singleton pattern in Swift. The first implementation shouldn’t be used, though. It merely illustrates a few concepts of the Swift language. 两种实现的方法，但是不应该用第一个来实现，仅仅是用他来说明swift语言的一些概念。</p>
<h3 id="Global-Variables"><a href="#Global-Variables" class="headerlink" title="Global Variables"></a>Global Variables</h3><p>The most straightforward technique to create a singleton is by defining a global variable.最简单最直接的办法就是创建一个全局变量。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sharedNetworkManager <span class="operator">=</span> <span class="type">NetworkManager</span>(baseURL: <span class="type">API</span>.baseURL)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NetworkManager</span> </span>&#123;</span><br><span class="line">        <span class="comment">// MARK: - Properties</span></span><br><span class="line">        <span class="keyword">let</span> baseURL: <span class="type">URL</span></span><br><span class="line">        <span class="comment">// Initialization</span></span><br><span class="line">        <span class="function"><span class="keyword">init</span>(<span class="params">baseURL</span>: <span class="type">URL</span>)</span> &#123;</span><br><span class="line">                <span class="keyword">self</span>.baseURL <span class="operator">=</span> baseURL</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>定义在全局的变量，任何在module里的对象都可以访问该变量。<br>By defining a variable in the global namespace of the project, any object in the module has access to the singleton object. We could, for example, access the singleton object in the <code>application(_:didFinishLaunchingWithOptions:)</code> method of the <code>AppDelegate</code> class.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">application</span>(<span class="keyword">_</span> <span class="params">application</span>: <span class="type">UIApplication</span>, <span class="params">didFinishLaunchingWithOptions</span> <span class="params">launchOptions</span>: [<span class="params">UIApplicationLaunchOptionsKey</span>: <span class="keyword">Any</span>]<span class="operator">?</span>)</span> -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">        <span class="built_in">print</span>(sharedNetworkManager)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>In Swift, global variables are initialized lazily. This means that the initializer is run the first time the global variable is referenced. <code>Swift</code>中全局变量只有被引用的时候才会被创建。</p>
<p>An added benefit of Swift’s approach is that the initialization is performed using the <code>dispatch_once</code> function. It guarantees that the initializer is invoked only once. That’s important since you only want to initialize the singleton object once.</p>
<p>Using a global variable has several shortcomings. The most important problem is cluttering the global namespace. Another downside is that the initializer of the <code>NetworkManager</code> class cannot be declared private. This means that multiple instances of the class <em>can</em> be instantiated. Let me show you a much better, and my preferred, implementation in Swift.<br>使用全局变量来申明单例有以下的缺点，第一就是污染了全局的命名空间。其二就是单例的初始化方法没有办法声明为<code>private</code>，这也就没有办法保证单例的唯一性。</p>
<h3 id="Static-Property-and-Private-Initializer"><a href="#Static-Property-and-Private-Initializer" class="headerlink" title="Static Property and Private Initializer"></a>Static Property and Private Initializer</h3><p>A few years ago, Swift introduced static properties and access control to the language. This opened up an alternative approach to implementing the singleton pattern in Swift. It’s much cleaner and elegant than using a global variable. Take a look at the updated example.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NetworkManager</span> </span>&#123;</span><br><span class="line">        <span class="comment">// MARK: - Properties</span></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">let</span> shared <span class="operator">=</span> <span class="type">NetworkManager</span>(baseURL: <span class="type">API</span>.baseURL)</span><br><span class="line">        <span class="comment">// MARK: -</span></span><br><span class="line">        <span class="keyword">let</span> baseURL: <span class="type">URL</span></span><br><span class="line">        <span class="comment">// Initialization</span></span><br><span class="line">        <span class="keyword">private</span> <span class="function"><span class="keyword">init</span>(<span class="params">baseURL</span>: <span class="type">URL</span>)</span> &#123;</span><br><span class="line">                <span class="keyword">self</span>.baseURL <span class="operator">=</span> baseURL</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>Accessing the singleton is intuitive and it clearly conveys that we’re dealing with a singleton.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">application</span>(<span class="keyword">_</span> <span class="params">application</span>: <span class="type">UIApplication</span>, <span class="params">didFinishLaunchingWithOptions</span> <span class="params">launchOptions</span>: [<span class="params">UIApplicationLaunchOptionsKey</span>: <span class="keyword">Any</span>]<span class="operator">?</span>)</span> -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">        <span class="built_in">print</span>(<span class="type">NetworkManager</span>.shared)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里有个几个实现细节的变化，第一就是初始化方法是私有的。也就意味着只有<code>NetworkManager</code>类能创建自己的实例。这是至关重要的第一点<br>Several implementation details have changed. First, the initializer is private. It means that only the <code>NetworkManager</code> class can create instances of itself. That’s a significant advantage.</p>
<p>第二我们申明了<code>shared</code>的<code>static constant property</code>属性，这个属性允许其他的对象访问到这个单例。<br>Second, we declared the <code>shared</code> static constant property. This property gives other objects access to the singleton object of the <code>NetworkManager</code> class.</p>
<p>这里不需要给<code>static properties</code>的属性加上<code>lazy</code>关键字，之前提到过全局变量默认的就是lazy的。<br>It isn’t necessary to mark static properties with the <code>lazy</code> keyword. Remember what I said earlier, the initializer of global variables and static properties are executed lazily by default. That’s another benefit.</p>
<p>I want to share one more implementation of the singleton pattern. This implementation is a bit more complex. The main difference is that the singleton object is instantiated in a closure, allowing for a more complex initialization and configuration of the singleton object.这里我将分享另外一种单例的实现，这种实现稍微有点复杂，主要的不同就是，对象的初始化是在一个<code>closure</code>中完成的，这也就允许更复杂的初始化和单例自身的配置。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NetworkManager</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// MARK: - Properties</span></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">var</span> sharedNetworkManager: <span class="type">NetworkManager</span> <span class="operator">=</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> networkManager <span class="operator">=</span> <span class="type">NetworkManager</span>(baseURL: <span class="type">API</span>.baseURL)</span><br><span class="line">        <span class="comment">// Configuration</span></span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">        <span class="keyword">return</span> networkManager</span><br><span class="line">        &#125;()</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// MARK: -</span></span><br><span class="line">        <span class="keyword">let</span> baseURL: <span class="type">URL</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// Initialization</span></span><br><span class="line">        <span class="keyword">private</span> <span class="function"><span class="keyword">init</span>(<span class="params">baseURL</span>: <span class="type">URL</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">self</span>.baseURL <span class="operator">=</span> baseURL</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// MARK: - Accessors</span></span><br><span class="line">        <span class="class"><span class="keyword">class</span> <span class="title">func</span> <span class="title">shared</span>() -&gt; <span class="title">NetworkManager</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> sharedNetworkManager</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>The static property is declared private. The singleton object is accessible through the <code>shared()</code> class method.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">application</span>(<span class="keyword">_</span> <span class="params">application</span>: <span class="type">UIApplication</span>, <span class="params">didFinishLaunchingWithOptions</span> <span class="params">launchOptions</span>: [<span class="params">UIApplicationLaunchOptionsKey</span>: <span class="keyword">Any</span>]<span class="operator">?</span>)</span> -&gt; <span class="type">Bool</span> &#123;</span><br><span class="line">        <span class="built_in">print</span>(<span class="type">NetworkManager</span>.shared())</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Cocoa-and-Singletons"><a href="#Cocoa-and-Singletons" class="headerlink" title="Cocoa and Singletons"></a>Cocoa and Singletons</h2><p>With these implementations in mind, we have mimicked the interface many Cocoa frameworks have adopted in Swift.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Shared URL Session</span></span><br><span class="line"><span class="keyword">let</span> sharedURLSession <span class="operator">=</span> <span class="type">URLSession</span>.shared</span><br><span class="line"></span><br><span class="line"><span class="comment">// Default File Manager</span></span><br><span class="line"><span class="keyword">let</span> defaultFileManager <span class="operator">=</span> <span class="type">FileManager</span>.default</span><br><span class="line"></span><br><span class="line"><span class="comment">// Standard User Defaults</span></span><br><span class="line"><span class="keyword">let</span> standardUserDefaults <span class="operator">=</span> <span class="type">UserDefaults</span>.standard</span><br><span class="line"></span><br><span class="line"><span class="comment">// Default Payment Queue</span></span><br><span class="line"><span class="keyword">let</span> defaultPaymentQueue <span class="operator">=</span> <span class="type">SKPaymentQueue</span>.default()</span><br></pre></td></tr></table></figure>

<h2 id="Are-Singletons-Bad"><a href="#Are-Singletons-Bad" class="headerlink" title="Are Singletons Bad"></a>Are Singletons Bad</h2><p>In <a target="_blank" rel="noopener" href="https://cocoacasts.com/are-singletons-bad/">Are Singletons Bad</a>, I explain in detail what type of problems the singleton pattern can introduce in a project. My advice is to use singletons sparingly. Very sparingly. If you’re about to create a singleton, take a moment and step back. Is there another option you may be overlooking? Is it absolutely necessary to use the singleton pattern?</p>
<p>Even though there’s nothing inherently wrong with singletons, most developers use it for the wrong reasons, that is, convenience. They disguise global variables as singletons.</p>
<h2 id="Dependency-Injection"><a href="#Dependency-Injection" class="headerlink" title="Dependency Injection"></a>Dependency Injection</h2><p>Even if you decide to use singletons in a project, that doesn’t mean you <em>have to</em> access them from anywhere in your project. You can still use dependency injection to pass the singleton object to the objects that need it.</p>
<p>By adopting dependency injection to pass singletons around, the interface of your class remains clear and transparent. In other words, the interface of the class describes its dependencies. This is very, very useful. It immediately shows which objects the class needs to perform its duties.</p>
<p>One of the things I miss about Objective-C is the header file. The header file summarizes the public interface of a class, including the dependencies of the class. This is sometimes less obvious in Swift.</p>

    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2018/12/21/Swift/String/" rel="prev" title="String">
      <i class="fa fa-chevron-left"></i> String
    </a></div>
      <div class="post-nav-item">
    <a href="/2018/12/21/Swift/Protocol/" rel="next" title="Protocol">
      Protocol <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Singleton"><span class="nav-number">1.</span> <span class="nav-text">Singleton</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#What-Is-a-Singleton-and-How-To-Create-One-In-Swift"><span class="nav-number">2.</span> <span class="nav-text">What Is a Singleton and How To Create One In Swift</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#What-Is-a-Singleton"><span class="nav-number">2.1.</span> <span class="nav-text">What Is a Singleton</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Global-Access"><span class="nav-number">2.2.</span> <span class="nav-text">Global Access</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#How-to-Create-a-Singleton-In-Swift"><span class="nav-number">2.3.</span> <span class="nav-text">How to Create a Singleton In Swift</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Global-Variables"><span class="nav-number">2.3.1.</span> <span class="nav-text">Global Variables</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Static-Property-and-Private-Initializer"><span class="nav-number">2.3.2.</span> <span class="nav-text">Static Property and Private Initializer</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cocoa-and-Singletons"><span class="nav-number">2.4.</span> <span class="nav-text">Cocoa and Singletons</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Are-Singletons-Bad"><span class="nav-number">2.5.</span> <span class="nav-text">Are Singletons Bad</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Dependency-Injection"><span class="nav-number">2.6.</span> <span class="nav-text">Dependency Injection</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">HR</p>
  <div class="site-description" itemprop="description">Swimming 🏊 in the sea🌊of code!</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:caohr@outlook.com" title="E-Mail → mailto:caohr@outlook.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HR</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
